package com.umfwechat.lightprogram.controller.pos;

import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.constant.CacheConsts;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.constant.ConfigConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.util.HttpUtil;
import com.umfwechat.util.MessageDigestUtil;
import com.umfwechat.util.RedisUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.StringUtil;
import com.umpay.sp.model.common.ReqMessage;
import com.umpay.sp.model.common.ResMessage;
import com.umpay.sp.model.saas.StoreInf;
import com.umpay.sp.service.saas.remote.StoreInfServiceRemote;
import com.umpay.sp.util.AmountUtil;
@Controller
@RequestMapping("/enterpriseController")
public class EnterpriseController {

	private static Logger logger = LoggerFactory.getLogger(EnterpriseController.class);
	@Resource
	private StoreInfServiceRemote storeInfServiceRemote;
	
	
	/**
	 * 补开pos
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/queryPosRate", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject queryPosRate(HttpServletRequest request, HttpServletResponse response) {
		JSONObject resultJson=new JSONObject();
		
		//从前台获取参数
		String reqJSON = (String) request.getAttribute(CommonConsts.REQUESTDATA);
		JSONObject param = null;
		try {
			param = JSONObject.fromObject(reqJSON);
		} catch (Exception e) {
			e.printStackTrace();
			resultJson.put(CommonConsts.RETCODE,RetCode.FAILURE);
			resultJson.put(CommonConsts.RETMSG, "请求参数不足");
			logger.error("----#---------#--补开pos信息数据转换异常--#---------#--",e);
			return resultJson;
		}
		String agentId = (String)param.get("loginAgentId");  //代理商账号
		String userId = (String)param.get("loginUserId");  //登录的userid
		
        String redisKey = CacheConsts.LOGIN+agentId+userId;
        //-------------取出缓存中的 assistid 和 password----------------------
        String redisValue = RedisUtil.get(redisKey);
        logger.info("从缓存中的 assistid 和 password---key="+redisKey+"value="+redisValue);
        //userId,assistId,password,其他
        String [] strArr = redisValue.split(",");
        String assistid = strArr[1];//用户名
        logger.info("-----------------assistid-------------------- " + assistid);
        String password = strArr[2];//密码
        logger.info("-----------------password-------------------- " + password);
        
		try {
			password = MessageDigestUtil.digest(password);
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
			logger.error("加密password报异常",e1);
		}//加密密码
        logger.info("-----------------加密后password-------------------- " + password);
		
        String storeId =(String)param.get(CommonConsts.STOREID);//店铺id
		if(StringUtil.isEmpty(storeId)){
			logger.info("店铺Id不能为空"+storeId);
			resultJson.put(CommonConsts.RETCODE,RetCode.FAILURE);
			resultJson.put(CommonConsts.RETMSG, "商铺不能为空");
			return resultJson;
		}
        // 店铺部署详情接口
		ReqMessage reqMe = ReqMessageUtil.makeSpReq();
		reqMe.getReqMap().put(CommonConsts.STOREID, storeId);
		ResMessage resMe = new ResMessage();
		try {
			logger.info("【店铺部署详情接口】输入参数 ：ReqMessage=" + reqMe);
			resMe = storeInfServiceRemote.getStoreInfByPri(reqMe);
			logger.info("【店铺部署详情接口】输出参数:ResMessage=" + resMe);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(String.format(storeId+"【店铺部署详情接口异常】"), e);
			resultJson.put(CommonConsts.RETCODE,RetCode.FAILURE);
			resultJson.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return resultJson;
		}

		// 获取店铺详情失败
		if (!RetCode.SUCCESS.equals(resMe.getRetCode())) {
			logger.info(storeId+"【店铺部署详情接口失败】");
			resultJson.put(CommonConsts.RETCODE,RetCode.FAILURE);
			resultJson.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return resultJson;
		}
		// 获取店铺简称信息
		StoreInf storeInf = (StoreInf) resMe.getResMap().get(CommonConsts.STOREINF);
        if(storeInf==null){
        	logger.info("【获取"+storeId+"店铺信息为空】");
			resultJson.put(CommonConsts.RETCODE,RetCode.FAILURE);
			resultJson.put(CommonConsts.RETMSG, "获取店铺信息失败");
			return resultJson;
        }
        String posReportId = storeInf.getPosReportId();//pos报备编号
        //商户进件信息详细查询
        String queryPosDetailsURL = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.QUERYPOSDETAILSURL);
       
        Map<String,Object> params = new HashMap<String,Object>();
		ReqMessage reqM = ReqMessageUtil.makeSpReq();
		params.put(CommonConsts.RPID, reqM.getRpid());
		params.put(CommonConsts.REQDATE, reqM.getReqDate());
		params.put(CommonConsts.REQTIME, reqM.getReqTime());
		params.put(CommonConsts.USER_ID,userId);
		params.put(CommonConsts.ASSIST_ID,assistid);
		params.put(CommonConsts.PASS_WORD,password);
		params.put(CommonConsts.DATASOURCE, "SAAS");
		params.put(CommonConsts.AGENTID, agentId);
		params.put(CommonConsts.MERID, posReportId);
		Map<String, Object> resultMap;
		try {
			logger.info("【商户进件信息详细查询】入参：" + params+"路径url"+queryPosDetailsURL);
			resultMap = HttpUtil.httpPostForm2Xml(queryPosDetailsURL, params);
			logger.info("【商户进件信息详细查询】出参：" + resultMap);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(storeId+"商户进件信息详细查询异常",e);
			resultJson.put(CommonConsts.RETCODE,RetCode.FAILURE);
			resultJson.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return resultJson;
		}
		
		if(!RetCode.SUCCESS.equals(resultMap.get(CommonConsts.RETCODE))){
			logger.info(storeId+"商户进件信息详细查询失败！");
			resultJson.put(CommonConsts.RETCODE,RetCode.FAILURE);
			resultJson.put(CommonConsts.RETMSG, "查询pos信息失败！");
			return resultJson;
		}
		String jfeerate =(String) resultMap.get(CommonConsts.JFEERATE);//借记卡费率	
		String debitCapamt =(String) resultMap.get(CommonConsts.DEBITCAPAMT);//借记卡封顶金额
		String dfeerate =(String) resultMap.get(CommonConsts.DFEERATE);//贷记卡费率
		
		BigDecimal divisor = new BigDecimal(100);   
		if(StringUtil.isNotEmpty(jfeerate)){
			BigDecimal jfee = new BigDecimal(jfeerate);   
		    jfeerate = jfee.divide(divisor,4,BigDecimal.ROUND_HALF_UP).toString();//借记卡费率/100
		}
		if(StringUtil.isNotEmpty(dfeerate)){
			BigDecimal dfee = new BigDecimal(dfeerate);   
		    dfeerate = dfee.divide(divisor,4,BigDecimal.ROUND_HALF_UP).toString();//贷记卡费率/100
		}
		String storeType = storeInf.getStoreType();//店铺类型
		if("0".equals(storeType)){
			storeType="小微商户";
		}else if("1".equals(storeType)){
			storeType="个体商户";
		}else if("2".equals(storeType)){
			storeType="企业商户";
		}
		resultJson.put(CommonConsts.RETCODE,RetCode.SUCCESS);
		resultJson.put(CommonConsts.STORESHORTNAME,storeInf.getStoreShortName());//店铺简称
		resultJson.put(CommonConsts.STORETYPE,storeType);//店铺类型
		resultJson.put(CommonConsts.JFEERATE,jfeerate);//借记卡费率
		resultJson.put(CommonConsts.DEBITCAPAMT,AmountUtil.Cent2Dollar2(debitCapamt));//借记卡封顶金额（分转元）
		resultJson.put(CommonConsts.DFEERATE,dfeerate);//贷记卡费率
		logger.info("【pos部署详情返回参数】：" + resultJson);
		return resultJson;
	}
	
	
	

	
}
